package client

import (
	"context"
	"fmt"
	"strings"
	"time"

	"gitee.com/xgotool/sqlite-logs-more/protoc"
	"gitee.com/xiaoyutab/xgotool/https"
)

// FMT日志输出
//
//	remote	远程地址
//	pipe	pipe识别码，自定义
//	content	日志内容
func PipeLog(remote, pipe, content string) {
	if remote == "" {
		fmt.Println(content)
		return
	}
	// 检测remote协议 协议长度小于5，即该协议既不是http也不是grpc
	if len(remote) < 5 {
		fmt.Println(content)
		return
	}
	if remote[len(remote)-1:] != "/" {
		remote += "/"
	}
	content = strings.TrimSpace(content)
	if content == "" {
		return
	}
	d := GetDervice(remote)
	if remote[0:4] == "http" {
		// 获取设备详情
		// 如果是http协议
		https.New(remote + "log.pipe.create").ParamJson(map[string]any{
			"id":      time.Now().UnixNano(),
			"did":     d.Id,
			"args":    pipe,
			"content": content,
		}).PostJson()
	} else if remote[0:4] == "grpc" {
		c := protoc.NewRemoteClient(client(remote))
		_, err := c.PipeLog(context.Background(), &protoc.Pipe{
			Id:      time.Now().UnixNano(),
			Args:    pipe,
			Content: content,
		})
		if err != nil {
			panic(err)
		}
	}
}
